package red.yancloud.www.ui.activity

import android.Manifest
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.PermissionRequest
import android.widget.ProgressBar
import android.widget.TextView
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.header.ClassicsHeader
import com.tbruyelle.rxpermissions2.RxPermissions
import com.tencent.smtt.export.external.interfaces.SslErrorHandler
import com.tencent.smtt.sdk.*
import kotlinx.android.synthetic.main.activity_feed_back.*
import kotlinx.android.synthetic.main.title_base_head.*
import red.yancloud.www.R
import red.yancloud.www.base.BaseActivity
import red.yancloud.www.ui.dialog.PermissionObtainDialog
import red.yancloud.www.ui.listener.OnClickPermissionListener
import red.yancloud.www.util.NetworkUtils
import red.yancloud.www.util.TimeFormatUtil
import red.yancloud.www.util.ToastUtils
import red.yancloud.www.util.UrlUtils
import java.text.SimpleDateFormat
import java.util.*

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/5/5 10:48
 * E_Mail：yh131412hys@163.com
 * Describe：我的-意见反馈
 * Change：
 * @Version：V1.0
 */
class FeedBackActivity : BaseActivity(), View.OnClickListener {

    private val TAG = "FeedBackActivity"

    private var client: MyChromeClient? = null

    override val layoutId: Int
        get() = R.layout.activity_feed_back

    override fun initData() {

        loadingDialog.show()

        webSetting()
        feedBackActivity_webView.webViewClient = MyWebViewClient()
        client = MyChromeClient(this, ProgressBar(mContext), TextView(mContext))
        feedBackActivity_webView.webChromeClient = client

        feedBackActivity_webView.clearCache(true)
        feedBackActivity_webView.clearHistory()
        feedBackActivity_webView.loadUrl(intent.getStringExtra("url"))

        grantedPermission()
    }

    override fun configViews() {

        back_iv.setOnClickListener(this)

        feedBackActivity_refreshLayout.setEnableRefresh(false)
        feedBackActivity_refreshLayout.setEnableLoadMore(false)
        val mClassicsHeader = feedBackActivity_refreshLayout.refreshHeader as ClassicsHeader
        mClassicsHeader.setLastUpdateTime(Date(System.currentTimeMillis()))
        mClassicsHeader.setTimeFormat(SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA))
        mClassicsHeader.setTimeFormat(TimeFormatUtil("更新于 %s"))

        feedBackActivity_refreshLayout.setOnRefreshListener { refreshLayout: RefreshLayout ->
            refreshLayout.layout.postDelayed(Runnable {

                if (!NetworkUtils.isConnected(mContext)) {
                    feedBackActivity_errorView.visibility = View.VISIBLE
                    ToastUtils.toastNetErrorMsg()
                    feedBackActivity_refreshLayout.finishRefresh()
                    return@Runnable
                }
            }, 1000)
        }
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.back_iv -> {

                finish()
            }
        }
    }

    internal var permissionListener: OnClickPermissionListener = object :
        OnClickPermissionListener {
        override fun permissionObtain() {
            grantedPermission()
        }
    }

    private fun grantedPermission() {
        RxPermissions(this).requestEach(
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE
        )
            .subscribe { permission ->
                if (permission.granted) {
                    // 用户已经同意该权限
                    Log.e(TAG, permission.name + " is granted.")
                } else if (permission.shouldShowRequestPermissionRationale) {
                    // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                    Log.e(TAG, permission.name + " is denied. More info should be provided.")
                    PermissionObtainDialog(this@FeedBackActivity, permissionListener).show()
                } else {
                    // 用户拒绝了该权限，并且选中『不再询问』
                    Log.e(TAG, permission.name + " is denied.")
                    PermissionObtainDialog(this@FeedBackActivity, permissionListener).show()
                }
            }
    }

    /**
     * 网页配置参数设置
     */
    @SuppressLint("JavascriptInterface")
    private fun webSetting() {
        val webSettings: WebSettings = feedBackActivity_webView.settings
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            webSettings!!.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
//        }
        webSettings.javaScriptCanOpenWindowsAutomatically = true
        webSettings.javaScriptEnabled = true
        feedBackActivity_webView.isFocusable = true
        feedBackActivity_webView.setBackgroundColor(0x00ffffff)
        feedBackActivity_webView.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY

        val  mHandler = Handler()
        feedBackActivity_webView.addJavascriptInterface(object : Any() {

            /**
             * 1、 加载json文件件,加载固定参数
             */
            @JavascriptInterface
            fun loadData() {
                mHandler.post {
                    try {
                        feedBackActivity_webView.loadUrl(
                            "javascript:waves("
                                    + UrlUtils.makeJsonText()
                                    + ")"
                        )

                        Log.d(TAG, "loadData: " + UrlUtils.makeJsonText())
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
        }, "demo")
    }

    private inner class MyWebViewClient : WebViewClient() {

        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            view.loadUrl(url)
            return true
        }

        override fun onPageStarted(view: WebView, url: String, favicon: Bitmap) {
            Log.d(TAG, "onPageStarted: $url")
        }

        override fun onPageFinished(view: WebView, url: String) {

            if (TextUtils.isEmpty(view.title)) {

                title_tv.text = "意见反馈"
            }else{

                title_tv.text = view.title
            }
            Log.d(TAG, "title: ${view.title}")
            loadingDialog.dismiss()
        }

        fun onReceivedSslError(
            view: WebView, handler: SslErrorHandler,
            error: SslError
        ) {

            Log.d(TAG, "onReceivedSslError: ")
            handler.proceed()
            loadingDialog.dismiss()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

        client!!.onActivityResult(requestCode, resultCode, data)
        super.onActivityResult(requestCode, resultCode, data)
    }

    inner class MyChromeClient(
        private val mActivity: Activity,
        private val bar: ProgressBar,
        private val mTitle: TextView
    ) : WebChromeClient() {

        private val CHOOSE_REQUEST_CODE = 0x9001
        private var uploadFile: ValueCallback<Uri>? = null//定义接受返回值
        private var uploadFiles: ValueCallback<Array<Uri>>? = null

        override fun onProgressChanged(view: WebView, newProgress: Int) {
            if (newProgress == 100) {
                bar.visibility = View.INVISIBLE
            } else {
                if (View.INVISIBLE == bar.visibility) {
                    bar.visibility = View.VISIBLE
                }
                bar.progress = newProgress
            }
            super.onProgressChanged(view, newProgress)
        }

        override fun onReceivedTitle(view: WebView, title: String) {

            super.onReceivedTitle(view, title)

            mTitle.text = title
        }

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        fun onPermissionRequest(request: PermissionRequest) {
            //                super.onPermissionRequest(request);//必须要注视掉
            request.grant(request.resources)
        }

        // For Android 3.0+
        fun openFileChooser(uploadMsg: ValueCallback<Uri>, acceptType: String) {
            this.uploadFile = uploadFile
            openFileChooseProcess()
        }

        // For Android < 3.0
        fun openFileChooser(uploadMsgs: ValueCallback<Uri>) {
            this.uploadFile = uploadFile
            openFileChooseProcess()
        }

        // For Android  > 4.1.1
        //    @Override
        override fun openFileChooser(uploadMsg: ValueCallback<Uri>, acceptType: String, capture: String) {
            this.uploadFile = uploadFile
            openFileChooseProcess()
        }

        // For Android  >= 5.0
        override fun onShowFileChooser(
            webView: WebView,
            filePathCallback: ValueCallback<Array<Uri>>,
            fileChooserParams: WebChromeClient.FileChooserParams
        ): Boolean {
            this.uploadFiles = filePathCallback
            openFileChooseProcess()
            return true
        }

        private fun openFileChooseProcess() {
            val i = Intent(Intent.ACTION_GET_CONTENT)
            i.addCategory(Intent.CATEGORY_OPENABLE)
            i.type = "image/*"
            mActivity.startActivityForResult(Intent.createChooser(i, "Choose"), CHOOSE_REQUEST_CODE)
        }

        fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            Log.d("requestCode===", "$requestCode====")
            if (resultCode == Activity.RESULT_OK) {
                when (requestCode) {
                    CHOOSE_REQUEST_CODE -> {
                        if (null != uploadFile) {
                            val result = if (data == null || resultCode != Activity.RESULT_OK)
                                null
                            else
                                data.data
                            uploadFile!!.onReceiveValue(result)
                            uploadFile = null
                        }
                        if (null != uploadFiles) {
                            val result = if (data == null || resultCode != Activity.RESULT_OK)
                                null
                            else
                                data.data
                            uploadFiles!!.onReceiveValue(arrayOf(result as Uri))
                            uploadFiles = null
                        }
                    }
                    else -> {
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                if (null != uploadFile) {
                    uploadFile!!.onReceiveValue(null)
                    uploadFile = null
                }
                if (null != uploadFiles) {
                    uploadFiles!!.onReceiveValue(null)
                    uploadFiles = null
                }
            }
        }
    }
}
